package com.ww.java7.path;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;

/**
 * @author wanggw
 * @Date 2023年03月01 0:31
 */
public class FileOperate {

    /**
     * Files类的文件创建、删除、写入、拷贝、读取写法，仅需一行代码
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        // 如果文件不存在，则创建一个文件
        Path path = Paths.get("D:/test/test.txt");
        Path pathBackup = Paths.get("D:/test/test_bak.txt");
        Path pathLink = Paths.get("D:/test/test.txt.link");
        Path pathDir = Paths.get("D:/test/dir");

        // 已存在则删除
        Files.deleteIfExists(path);
        Files.deleteIfExists(pathBackup);
        Files.deleteIfExists(pathLink);
        Files.deleteIfExists(pathDir);

        // 创建文件写入内容
        Path file = Files.createFile(path);
        Files.write(path, "张三".getBytes());
        Files.write(path, System.lineSeparator().getBytes(), StandardOpenOption.APPEND);
        Files.write(path, "令狐少侠".getBytes(), StandardOpenOption.APPEND);
        System.out.println("创建文件：" + file.toString());

        // 创建文件链接
        pathLink = Files.createLink(pathLink, path);
        System.out.println("创建文件：" + pathLink.toString());

        // 创建目录
        Path directory = Files.createDirectory(pathDir);
        System.out.println("创建目录：" + directory.toString());

        // 文件复制
        Files.copy(path, pathBackup);
        System.out.println("复制文件：" + path + " --> " + pathBackup);

        List<String> lines = Files.readAllLines(pathBackup);
        for (String line : lines) {
            System.out.println("文件读取：" + line);
        }
    }
}
